package com.dave.gd.service.impl;

import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.dave.gd.config.sysmgr.SysmgrConstants;
import com.dave.gd.service.IUserService;
import com.dave.gd.sysmgr.domain.entity.User;
import com.dave.gd.sysmgr.domain.entity.UserInfo;
import com.dave.gd.sysmgr.domain.mapper.UserInfoMapper;
import com.dave.gd.sysmgr.domain.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class UserService implements IUserService {
    private static Logger log = Logger.getLogger(UserService.class);
    @Resource
    private UserMapper userDao;
    @Resource
    private UserInfoMapper userInfoDao;
    
    @Override
    public int insert(User t) {
        Date date = new Date();
        Timestamp ttamp = new Timestamp(date.getTime());
        t.setLastAccessTime(ttamp);
        t.setDeleted(SysmgrConstants.NO_STATE);
        int id = this.userDao.insert(t);
        log.info("UserService==>insert:插入成功，返回数字为：" + id);
        return id;
    }
    
    @Override
    public int delete(long id) {
        return del(id);
    }
    
    private int del(long id) {
        User u = new User();
        u.setId((int) id);
        Date date = new Date();
        Timestamp ttamp = new Timestamp(date.getTime());
        u.setDeleteTime(ttamp);
        u.setDeleted(SysmgrConstants.NO_STATE);
        int uid = this.userDao.deleteById(id);
        UserInfo ui = new UserInfo();
        ui.setId(this.userInfoDao.qyeryByUid((int) id).getId());
        ui.setDeleted(SysmgrConstants.NO_STATE);
        ui.setDeleteTime(ttamp);
        int uiid = this.userInfoDao.update(ui);
        if (uid == uiid) {
            return uid;
        } else {
            return 0;
        }
    }
    
    @Override
    public int update(User t) {
        return this.userDao.update(t);
    }
    
    @Override
    public User get(long id) {
        return this.userDao.queryById(id);
    }
    
    @Override
    public Page<User> queryPage(Integer pageNum, Integer pageSize, User t) {
        PageHelper.startPage(pageNum, pageSize);
        Page<User> pu = this.userDao.queryPage(t);
        
        return pu;
    }
    
    @Override
    public int lastAccessTime() {
        User t = new User();
        Date date = new Date();
        Timestamp ttamp = new Timestamp(date.getTime());
        t.setLastAccessTime(ttamp);
        return this.userDao.update(t);
    }
}
